import { isBoolean } from 'lodash-es';

import type { PaginationProps } from '../types/pagination';
import { DEFAULTPAGESIZE, PAGESIZES } from '../const';

import type { BasicTableProps } from '@/components/table/src/props';

export function usePagination(refProps: ComputedRef<BasicTableProps>) {
  const configRef = ref<PaginationProps>({});

  const getPaginationInfo = computed((): PaginationProps | boolean => {
    const { pagination } = unref(refProps);
    if (!pagination) {
      return false;
    }
    return {
      page: 1,
      pageSize: DEFAULTPAGESIZE,
      pageSizes: PAGESIZES,
      showSizePicker: true,
      showQuickJumper: true,
      prefix: (pagingInfo: PaginationProps) => `共 ${pagingInfo.itemCount} 条`,
      ...(isBoolean(pagination) ? {} : pagination),
      ...unref(configRef),
    };
  });

  function setPagination(info: Partial<PaginationProps>) {
    const paginationInfo = unref(getPaginationInfo);
    configRef.value = {
      ...(!isBoolean(paginationInfo) ? paginationInfo : {}),
      ...info,
    };
  }

  function getPagination() {
    return unref(getPaginationInfo);
  }

  return {
    getPagination,
    getPaginationInfo,
    setPagination,
  };
}
